package net.stogi.dsper.ui.server.module.user;

import net.stogi.common.gwt.dispatch.server.core.ActionHandler;
import net.stogi.common.gwt.dispatch.shared.exception.ActionException;
import net.stogi.common.security.service.SecurityService;
import net.stogi.dsper.api.service.UserService;
import net.stogi.dsper.ui.shared.module.user.ListUserProfilesAction;
import net.stogi.dsper.ui.shared.module.user.ListUserProfilesResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("DsperUi.Dispatch.ListUserProfilesActionHandler")
public class ListUserProfilesActionHandler implements ActionHandler<ListUserProfilesAction, ListUserProfilesResult> {

	private static final Logger log = LoggerFactory.getLogger(ListUserProfilesActionHandler.class);

	@Autowired
	private SecurityService securityService;

	@Autowired
	private UserService userService;

	@Override
	public ListUserProfilesResult execute(ListUserProfilesAction action) throws ActionException {
		log.trace("execute(): invoke [ action = '{}']", action);

		ListUserProfilesResult result;

		try {
			Long userId = userService.getUserByUsername(securityService.getLoggedUserPrincipalData().getUsername()).getId();

			result = new ListUserProfilesResult(userService.listUserProfiles(userId));
		}
		catch (Exception e) {
			throw new ActionException(e);
		}

		return result;
	}

	@Override
	public Class<ListUserProfilesAction> getActionType() {
		return ListUserProfilesAction.class;
	}

	@Override
	public void rollback(ListUserProfilesAction action, ListUserProfilesResult result) throws ActionException {}
}
